package cn.foolishbird.crow.core.util;

import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 *
 * @author foolishbird
 */
public class UniqueValueCheckUtils {

    /**
     * 唯一校验
     * @param values
     * @param <T>
     * @return
     */
    public static <T, R>  boolean unique(Collection<? extends T> values, Function<T, R> function) {
        return unique(values, function, o -> true);
    }

    /**
     * 唯一校验
     * @param values
     * @param predicate
     * @param <T>
     * @return
     */
    public static <T, R> boolean unique(Collection<? extends T> values, Function<T, R> function,
                                        Predicate<Collection<? extends T>> predicate) {
        if (CollectionUtils.isEmpty(values)) {
            return true;
        }
        Set<R> set = Sets.newHashSetWithExpectedSize(values.size());
        Optional<R> optional = values.stream()
                .map(function::apply)
                .filter(v -> !set.add(v)).findFirst();
        return !optional.isPresent() && predicate.test(values);
    }

}
